import { useUserStore } from "@/stores/user"
import { ElMessageBox } from "element-plus"
import router from '@/router'; // 假设router被导出  
/**
 * 获取当前用户的权限token
 * @returns {string} 用户token
 */
const getPermission = () => {
  const userStore = useUserStore()
  return userStore.token
}

export default {
  mounted(el, binding) {
    const handleClick = (event) => {  
      if (!getPermission()) {
        event.preventDefault(); 
        event.stopPropagation();
        event.stopImmediatePropagation(); // 关键代码 用来阻止事件继续传播到其他事件监听器。
        // 没有权限
        ElMessageBox.confirm('请先登录后继续操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // 跳转登录页面
          router.push({
            path: '/login',
            query: { redirect: router.currentRoute.value.fullPath },
          })
        }).catch(() => {
        }) 
        return false
      }
    }
    el.addEventListener('click', handleClick, true)
      // 保存事件移除函数，便于卸载时清理
    el._clickHandler = handleClick;
  },
  unmounted(el) { 
    // 移除事件监听
    const handler = el._clickHandler;
    if (handler) {
      el.removeEventListener('click', handler, true);
    }
  },

}